<template>
    <div>
       <!-- 面包屑导航区域 -->
       <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>权限列表</el-breadcrumb-item>
       </el-breadcrumb>

       <!-- 卡片视图区 -->
       <el-card>
           <el-row>
               <el-col>
                   <el-button type="primary" @click="addRolesDialog=true">添加角色</el-button>
               </el-col>
           </el-row>
           <el-table :data="rolesList" stripe border>
               <el-table-column type="expand">
                   <template slot-scope="scope">
                       <el-row :gutter="24" v-for="(item1,i1) in scope.row.children" :key="item1.id"  :class="['bdbottom',i1 === 0?'bdtop':'','vcenter']">
                            <!-- 渲染一级权限 -->
                            <el-col :span="5">
                                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 渲染二级和三级权限 -->
                            <el-col :span="19">
                                <el-row :gutter="24" v-for="(item2,i2) in item1.children" :key="item2.id"  :class="[i2 === 0?'':'bdtop','vcenter']">
                                    <el-col :span="6">
                                        <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="18">
                                        <el-tag type="warning" v-for="(item3) in item2.children" :key="item3.id" closable @close="removeRightById(scope.row,item3.id)">{{item3.authName}}</el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                   </template>
               </el-table-column>
               <el-table-column label="#" type="index"></el-table-column>
               <el-table-column label="角色名称" prop="roleName"></el-table-column>
               <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
               <el-table-column label="操作" width="340px">
                    <template  slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="editRole(scope.row.id)" >编辑
                        </el-button>
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeRolesById(scope.row.id)">删除
                        </el-button>
                        <el-button type="warning" icon="el-icon-setting" size="mini" @click="showRightDialog(scope.row)">分配权限
                        </el-button>
                    </template>
               </el-table-column>
            </el-table>

           <!-- 添加角色的对话框 -->
            <el-dialog title="添加角色" :visible.sync="addRolesDialog" width="50%" @close="addRoleClose">
                <!-- 添加角色主体区域 -->
                <el-form ref="addRole_ref" :model="addRole" :rules="addRole_rules" label-width="100px">
                    <!-- 角色名称 -->
                    <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addRole.roleName" ></el-input>
                    </el-form-item>
                    <!-- 角色描述-->
                    <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="addRole.roleDesc"></el-input>
                    </el-form-item>
                </el-form>
                <!-- 添加角色底部区域 -->
                <span slot="footer" class="dialog-footer">
                <el-button @click="addRolesDialog = false">取 消</el-button>
                <el-button type="primary" @click="addRoleConfirm">确 定</el-button>
            </span>
            </el-dialog>

            <!-- 修改角色的对话框 -->
            <el-dialog title="修改角色" :visible.sync="editRoleDialog"  width="50%" @close="editRoleClose">
                <el-form ref="editRole_ref" :model="editRoleList" :rules="editRole_rules" label-width="100px">
                    <el-form-item label="角色id">
                        <el-input v-model="editRoleList.roleId" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="角色名称" prop="roleName">
                        <el-input v-model="editRoleList.roleName" ></el-input>
                    </el-form-item>
                    <el-form-item label="角色描述">
                        <el-input v-model="editRoleList.roleDesc"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="editRoleDialog = false">取 消</el-button>
                    <el-button type="primary" @click="editRoleInfo">确 定</el-button>
                </span>
            </el-dialog>

            <!-- 分配权限的对话框 -->
            <el-dialog title="分配权限" :visible.sync="rightDialogVisible"  width="50%" @close="rightDialogClose">
               <el-tree ref="treeRef" :data="rightList" :props="rightProps"  show-checkbox node-key="id" default-expand-all :default-checked-keys="defkeys"></el-tree>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="rightDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="allowRight">确 定</el-button>
                </span>
            </el-dialog>
       </el-card>
    </div>
</template>

<script>
export default {
    data(){
        return {
            rolesList:[],
            addRole:{
               roleName:'',
               roleDesc:''
            },
            // 添加角色的表单验证规则
            addRole_rules:{
              roleName:[{ required: true, message: '请输入角色名称', trigger: 'blur' }],
              roleDesc:[{ required: true, message: '请输入角色描述', trigger: 'blur' }]
            },
            addRolesDialog:false,
            // 修改角色相关数据和规则
            editRoleList:{},
            editRoleDialog:false,
            editRole_rules:{
                 roleName:[{ required: true, message: '请输入角色名称', trigger: 'blur' }]
            },
            rightDialogVisible:false,
            rightList:[],
            rightProps:{
                children:'children',
                label:'authName'
            },
            defkeys:[],
            roleId:''

        }
    },
    created(){
        this.getRolesList()
    },
    methods:{
      //获取角色列表
      async getRolesList(){
          const {data:res} = await this.$http.get('roles');
        //   console.log(res);
          if(res.meta.status !== 200){return this.$message.error('获取角色列表失败')};
          this.rolesList = res.data;
      },
      addRoleClose(){
          this.$refs.addRole_ref.resetFields();
      },
       // 添加角色
      addRoleConfirm(){ 
        this.$refs.addRole_ref.validate(async valid =>{
            const {data:res} = await this.$http.post('roles',this.addRole);
            if(res.meta.status !== 201){return this.$message.error('添加角色失败')};
            this.$message.success('添加角色成功');
            this.getRolesList();
        })
          
      },
      // 修改角色
      async editRole(id){
            this.editRoleDialog = true;
            const {data:res} = await this.$http.get('roles/'+id);
            this.editRoleList = res.data;
       },
      editRoleClose(){
            this.$refs.editRole_ref.resetFields();
        },
      async editRoleInfo(){
            const {data:res} =await this.$http.put('roles/'+this.editRoleList.roleId,{
                roleName:this.editRoleList.roleName,
                roleDesc:this.editRoleList.roleDesc});
            // console.log(res);
            if(res.meta.status !==200){return this.$message.error('修改角色失败') };
            this.editRoleDialog = false;
            this.$message.success('修改角色成功')
            this.getRolesList();
        },
      // 删除角色
      async removeRolesById(id){
            // console.log(id);
            const confirmRes =await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(error => error);
            if (confirmRes !== 'confirm'){return this.$message.info('已取消删除角色')};
            const {data:res} =await this.$http.delete('roles/'+id)
            if(res.meta.status != 200) {return this.$message.error('删除角色失败')};
            this.getRolesList();
            this.$message.success('删除角色成功')
        },
      
       // 删除角色的权限  
      async removeRightById(role,rightId){
            // console.log(id);
            const confirmRes =await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(error => error);
            if (confirmRes !== 'confirm'){return this.$message.info('已取消删除权限')};
            const {data:res} =await this.$http.delete(`roles/${role.id}/rights/${rightId}`);
            // console.log(res);
            if(res.meta.status != 200) {return this.$message.error('删除权限失败')};
            role.children = res.data;
        },
        // 分配权限的对话框渲染
      async showRightDialog(role){
          this.roleId = role.id
          const {data:res} = await this.$http.get('rights/tree');
          if (res.meta.status !== 200){return this.$message.error('获取权限列表失败')};
          this.rightList = res.data;
          this.getLeafKeys(role, this.defkeys)
          this.rightDialogVisible = true;
       },
        // 获取三级权限的Id
       getLeafKeys(node, arr){
           if(!node.children){
               return arr.push(node.id)
           };
           node.children.forEach(item => {
              this.getLeafKeys(item, arr) 
           });
       },
        // 监测分配权限对话框关闭时重置
       rightDialogClose(){
           this.defkeys = [];
       },
        //为角色分配权限
       async allowRight(){
           const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()];
        //    console.log(keys);
            const keysStr = keys.join(',');
            // console.log(keysStr);
            const {data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids:keysStr});
            if (res.meta.status != 200) {
                return this.$message.error('更新权限失败')
            }
            this.$message.success('更新权限成功');
            this.getRolesList();
            this.rightDialogVisible = false;
       }
    }
    
}
</script>

<style lang="less" scoped>
.el-tag{
    margin: 7px;
}

.bdtop{
    border-top: 1px solid #eeeeee;
}

.bdbottom{
    border-bottom: 1px solid #eeeeee;
}

.vcenter{
    display: flex;
    align-items: center;
}
</style>